<template>
    <div class="text-sm ">
        <div class="relative bg-white" :="$attrs">
            <div class="flex items-end h-8 px-3 space-x-2 overflow-x-auto text-center text-gray-500 whitespace-nowrap"
                :class="{ ' justify-around': full }">
                <div ref="tabRef" class="inline-block px-2 transition-all"
                    :class="{ 'font-bold text-gray-700': index == selfActive }" v-for="(tab, index) in tabs"
                    @click="selfActive = index">
                    {{ tab }}
                </div>
            </div>
            <div ref="activeRef" class="absolute text-2xl text-red-500 transition-all duration-300" :="activeAttrs"
                :class="{ '-rotate-90 top-2/3': activeElPosition == 'b', 'top-1/2  -rotate-135 -translate-x-2': activeElPosition == 'br' }">
                <IGg:shape-half-circle />
            </div>
        </div>
        <div>
            <slot />
        </div>
    </div>
</template>
    
<script setup lang='ts'>
const $props = withDefaults(
    defineProps<{
        full?: boolean,
        activeElPosition?: 'b' | 'br',
        activeAttrs?:any
    }>(),
    {
        activeElPosition: 'b',
    }
)
const active = defineModel('active', { default: 0 });
const selfActive = ref(active.value);
const tabs = ref<string[]>([]);
const activeRef = ref();
const tabRef = ref<HTMLElement[]>([]);
const $emits = defineEmits<{
    (e: 'change', index: number): void;
}>()

const setActive = () => {
    const tab = tabRef.value[selfActive.value];
    if (!tab) {
        return
    }
    const { left, width } = tab.getBoundingClientRect();
    const offset = $props.activeElPosition == 'b' ? (width / 2) : width;
    activeRef.value.style.left = (left - (activeRef.value.clientWidth / 2) + offset) + 'px'
}

provide('tabs', {
    add(name: string) {
        tabs.value.push(name);
    },
    setActive(name: string) {
        selfActive.value = tabs.value.indexOf(name);
    },
    currentTab: computed(() => tabs.value[selfActive.value])
})

watchEffect(() => {
    active.value = selfActive.value;
    $emits('change', selfActive.value)
    setActive()
})
defineOptions({
    inheritAttrs: false
})
</script>
    
<style></style>